package com.wang.system.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.common.aes.AESEncryptService;
import com.wang.common.result.Result;
import com.wang.common.result.ResultCodeEnum;
import com.wang.common.utils.JwtHelper;
import com.wang.entity.model.LoginModel;
import com.wang.entity.model.SysUserModel;
import com.wang.entity.system.SysUser;
import com.wang.entity.vo.SysUserVo;
import com.wang.system.config.TenantContext;
import com.wang.system.service.system.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;

/**
 * @Author wang
 * @Date 2024/9/22 1:18
 * @PackageName:com.wang.system.controller.system
 * @ClassName: SysUserController
 * @Description: TODO
 * @Version 1.0
 */
@RestController
@Api(tags = "系统用户管理")
@RequestMapping("/admin/system/user")
public class SysUserController {

    @Autowired
    private JwtHelper jwtHelper;

    @Autowired
    private SysUserService userService;

    @Autowired
    private AESEncryptService aesEncryptService;

//    @Autowired
//    private PasswordEncoder passwordEncoder;

    // 登录接口
    @PostMapping("/login")
    @ApiOperation(value = "登录", notes = "登录接口")
    public Result<LinkedHashMap<String, Object>> login(@RequestBody LoginModel model) {
        // 设置当前登录用户的租户ID
        TenantContext.setTenantId(model.getTenantId());

        SysUserVo user = userService.findByUsername(model.getUsername());

        if (user == null || !aesEncryptService.decrypt(user.getPassword()).equals(model.getPassword())) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            map.put("data", ResultCodeEnum.USERNAME_OR_PASSWORD_ERROR.getMessage());
            return Result.fail(map);
        }


        // 生成 JWT token
        String token = jwtHelper.createToken(user.getTenantId(), user.getId(), user.getUsername());
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("tenantId", user.getTenantId());
        map.put("userId", user.getId());
        map.put("username", user.getUsername());
        map.put("user", user);
        map.put("token", token);
        return Result.ok(map);
    }

    @PostMapping("/logout")
    @ApiOperation(value = "退出登录", notes = "退出登录接口")
    public Result<?> logout() {
        // 清除租户信息
        TenantContext.clear();
        return Result.ok();
    }

    // 注册接口
    @PostMapping("/register")
    @ApiOperation(value = "注册", notes = "注册接口")
    public Result<?> register(@RequestBody LoginModel model) {

            if (userService.existsByUsername(model.getUsername()) > 0) {
                return Result.fail(ResultCodeEnum.USERNAME_EXIST);
            }


            SysUser user = new SysUser();
            user.setTenantId(model.getTenantId());
            user.setUsername(model.getUsername());
            // 使用 AES 加密用户的密码
            String encryptedPassword = aesEncryptService.encrypt(model.getPassword());
            user.setPassword(encryptedPassword);
            userService.save(user);

            return Result.ok(ResultCodeEnum.SUCCESS);

    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "用户列表", notes = "用户列表接口")
    public Result<IPage<SysUserVo>> queryPageList(SysUserModel sysUser, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SysUserVo> page = new Page<>(pageNo, pageSize);

        return Result.ok(userService.queryPageList(sysUser, page));
    }

    // 禁用/启用用户
    @PutMapping(value = "/{userId}/status/{status}")
    @ApiOperation(value = "禁用/启用用户", notes = "禁用/启用用户接口")
    public Result<?> updateStatus(@PathVariable("userId") Long userId, @PathVariable("status") Integer status) {
        SysUser user = userService.getById(userId);
        if (user == null) {
            return Result.fail(ResultCodeEnum.USER_NOT_EXIST);
        }
        user.setStatus(status); // 0 禁用 1 启用
        userService.updateById(user);
        return Result.ok(ResultCodeEnum.SUCCESS);
    }

    // 删除用户
    @DeleteMapping(value = "/{userId}")
    @ApiOperation(value = "删除用户", notes = "删除用户接口")
    public Result<?> deleteUser(@PathVariable("userId") Long userId) {
        SysUser user = userService.getById(userId);
        if (user == null) {
            return Result.fail(ResultCodeEnum.USER_NOT_EXIST);
        }
        userService.removeById(userId);
        return Result.ok(ResultCodeEnum.SUCCESS);
    }

    // 批量删除用户
    @DeleteMapping(value = "/batch")
    @ApiOperation(value = "批量删除用户", notes = "批量删除用户接口")
    public Result<?> deleteBatch(@RequestBody Long[] userIds) {
        for (Long userId : userIds) {
            SysUser user = userService.getById(userId);
            if (user == null) {
                return Result.fail(ResultCodeEnum.USER_NOT_EXIST);
            }
            userService.removeById(userId);
        }
        return Result.ok(ResultCodeEnum.SUCCESS);
    }

    // 回收站列表查询
    @GetMapping(value = "/recycle")
    @ApiOperation(value = "回收站列表查询", notes = "回收站列表查询接口")
    public Result<IPage<SysUserVo>> queryRecycleList(SysUserModel sysUser, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SysUserVo> page = new Page<>(pageNo, pageSize);

        return Result.ok(userService.queryRecycleList(sysUser, page));
    }


    // 回收站恢复删除用户
    @PutMapping(value = "/recycle/{userId}")
    @ApiOperation(value = "回收站恢复删除用户", notes = "回收站恢复删除用户接口")
    public Result restoreUser(@PathVariable("userId") Long userId) {
        SysUser user = userService.getRecycleById(userId);
        if (user == null) {
            return Result.fail(ResultCodeEnum.USER_NOT_EXIST);
        }
        user.setIsDeleted(0);
        userService.updateRecycleById(user);
        return Result.ok(ResultCodeEnum.SUCCESS);
    }
}
